package com.helloandroid

import android.content.Intent
import android.widget.RadioGroup
import androidx.core.content.edit
import androidx.fragment.app.Fragment
import com.hby.game.HbyGame
import com.helloandroid.activitys.BuShuDaKaActivity
import com.helloandroid.activitys.ChiFanActivity
import com.helloandroid.ads.NativeAdUtil
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.base.BaseActivity
import com.helloandroid.tools.*
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.zp.game.ZpGame
import dai.android.util.AndroidUtils

class MainActivity : BaseActivity() {

    companion object {
        const val keyZou = "zou"
        const val keyZhuan = "zhuan"
        const val keyWode = "wode"
    }

    // view-binding 文档
    // https://developer.android.com/topic/libraries/view-binding
    private var curKey: String? = null
    private lateinit var rgTab: RadioGroup
    var where = -1

    override fun getContentViewResId() = R.layout.app_activity_main
    override fun initView() {
        MyLog.elog("*************initView called!")
        where = intent.getIntExtra(IntentKey.ComeFromWhere, -1)
        rgTab = findViewById(R.id.rgTab)
        rgTab.setOnCheckedChangeListener { _: RadioGroup, _: Int ->
            if (AppUtil.isLogin) {
                updateFragment()
            } else {
                rgTab.check(R.id.rbZouzou)
                AppUtil.toast("请先进行登陆!")
            }
        }
        updateFragment()
    }


    fun isHbyPending() = where == IntentValue.Int_Hby

    fun checkComeFrom() {
        MyLog.elog("========checkComeFrom called!===========where:${where}=======")
        when (where) {
            IntentValue.Int_BuShu -> {
                // 直接跳转到吃饭
                startActivity(Intent(this, BuShuDaKaActivity::class.java))
            }
            IntentValue.Int_Hby -> {
                if (!AppUtil.isHbyTodayCompleted() && AppUtil.isHbyCanPlay()) {
                    startActivity(Intent(this, HbyGame::class.java))
                } else {
                    AppUtil.toast("红包雨还未开始.....")
                }
            }
            IntentValue.Int_ChiFan -> {
                // 直接跳转到吃饭
                startActivity(Intent(this, ChiFanActivity::class.java))
            }

            IntentValue.Int_Sign -> {
                // 签到
                swithToZhuanFragment()
            }

            IntentValue.Int_ZhuanPan -> {
                // 转盘
                startActivity(Intent(this, ZpGame::class.java))
            }
            IntentValue.Int_Resdient -> {
                // 到 zouFragment
                swithToZouFragment()
            }
            -1 -> {
                MyLog.elog(" 正常启动.....")
            }
        }
        where = -1
    }

    fun swithToZouFragment() {
        rgTab.check(R.id.rbZouzou)
    }

    private fun swithToZhuanFragment() {
        rgTab.check(R.id.rbZhuanzhuan)
    }

    fun swithToWodeFragment() {
        rgTab.check(R.id.rbWode)
    }

    override fun initData() {
        // local
        // 检查是否需要弹
        if (!AndroidUtils.isNotificationEnabled(this)) {
            // 检查
            val pref = MyApplication.getPerference(AppConfig.Pref_Local)
            val lastToastTime = pref.getLong(AppConfig.KeyLastToastTime, -1L)
            val totalCount = pref.getInt(AppConfig.KeyToastCount, 0)
            if (lastToastTime <= 0) {
                // 首次登陆,不弹
                pref.edit(commit = true) {
                    putLong(AppConfig.KeyLastToastTime, AppUtil.sysTime)
                }
            } else {
                if (totalCount >= 3) {
                    // 已经弹了3次
                    return
                } else {

                    val todayTimeStamp = MyTimeUtils.dayTimeString(AppUtil.sysTime)
                    val lastTimeStamp = MyTimeUtils.dayTimeString(lastToastTime)

                    // 还要判断今天是否弹了
                    if (todayTimeStamp == lastTimeStamp) {
                        return
                    } else {
                        pref.edit(commit = true) {
                            putLong(AppConfig.KeyLastToastTime, AppUtil.sysTime)
                            putInt(AppConfig.KeyToastCount, totalCount + 1)
                        }

                        // 弹
                        XXPermissions.with(this)
                                .permission(Permission.NOTIFICATION_SERVICE)
                                .request { _, all ->
                                    if (all) {
                                        AppUtil.startBgService()
                                    }
                                }
                    }
                }
            }
        }
    }

    private fun createFragment(key: String): Fragment {
        MyLog.elog("createFragment called!")
        return when (key) {
            keyZou -> ZouzouFragment()
            keyZhuan -> ZhuanzhuanFragment()
            keyWode -> WodeFragment()
            else -> throw RuntimeException("unknow fragment key:$key")
        }
    }

    private fun updateFragment() {

        val newKey = when (rgTab.checkedRadioButtonId) {
            R.id.rbZouzou -> keyZou
            R.id.rbZhuanzhuan -> keyZhuan
            else -> keyWode
        }

        if (newKey == curKey) {
            return
        }

        curKey = newKey
        val fragment = createFragment(newKey)
        supportFragmentManager.beginTransaction().replace(R.id.flMain, fragment).commit()
    }

    override fun onDestroy() {
        super.onDestroy()
        MyLog.elog("Main Activity onDestroy called!")
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        MyLog.elog("*************onNewIntent called!")

        intent?.let {
            where = it.getIntExtra(IntentKey.ComeFromWhere, -1)
            checkComeFrom()
        }
    }

    // 上次按 back 按键的时间
    var pressBackTimeMs = 0L
    override fun onBackPressed() {

        when (curKey) {
            keyZou -> {
                if (System.currentTimeMillis() - pressBackTimeMs >= 2000L) {
                    AppUtil.toast("再按一次退出!")
                    pressBackTimeMs = System.currentTimeMillis()
                } else {
                    super.onBackPressed()
                }
            }
            keyZhuan -> {
                swithToZouFragment()
            }
            keyWode -> {
                swithToZouFragment()
            }
            else -> {
                // do nothing...
            }
        }
    }
}